<template>
	<div>
		<grid class="myPoCusGridTitle" :show-vertical-dividers="false">
			<grid-item @click.native="orderByFunc('name')">
				<span class="grid-center" style="margin-left: 10px;">姓名<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
			<grid-item @click.native="orderByFunc('tag')">
				<span class="grid-center" style="margin-left: 10px;">评级<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
			<grid-item @click.native="orderByFunc('stage')">
				<span class="grid-center" style="margin-left: 10px;">阶段<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
			<grid-item class="myPoCusStatus" @click.native="orderByFunc('time')">
				<span class="grid-center-status">状态<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
			<grid-item @click.native="orderByFunc('employee')">
				<span class="grid-center">咨询<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
		</grid>

		<scroller :on-refresh="refresh" :on-infinite="infinite" :noDataText="noDataText" ref="poStudentList">
			<group id="commonScroller" class="commonScrollerAllPoCustomer">
				<grid class="myPoCusGrid" v-for="(item,index) in items" :show-vertical-dividers="false">
					<grid-item class="grid-item" @click.native="jumpTo(item.id)">
						<span class="grid-center-name">{{item.name.substring(0,3)}}</span>
					</grid-item>
					<grid-item class="grid-item" @click.native="showLevelPop(item, index)">
						<span v-if="item.tag == null" class="grid-center">无<img slot="icon" class="grid-img-select" src="@/assets/svg/icon_corner.svg"></span>
						<span v-else class="grid-center">{{item.tag}}<img slot="icon" class="grid-img-select" src="@/assets/svg/icon_corner.svg"></span>
					</grid-item>
					<grid-item class="grid-item" @click.native="showStagePop(item, index)">
						<span v-if="item.stage == null" class="grid-center">无<img slot="icon" class="grid-img-select" src="@/assets/svg/icon_corner.svg"></span>
						<span v-else class="grid-center">{{item.stage}}<img slot="icon" class="grid-img-select" src="@/assets/svg/icon_corner.svg"></span>
					</grid-item>
					<grid-item class="myPoCusStatus">
						<span v-if="item.time == null" class="grid-center-status">无</span>
						<span v-else-if="item.comments == null" class="grid-center-status">{{formatTime(item.time) + '，没有备注'}}</span>
						<span v-else class="grid-center-status">{{formatTime(item.time) + '，' + item.comments.substring(0,5)}}</span>
					</grid-item>
					<grid-item class="grid-item">
						<span class="grid-center">{{item.employee}}</span>
					</grid-item>
				</grid>
			</group>
		</scroller>

		<div v-transfer-dom>
			<popup v-model="showLevel" :hide-on-blur=false height="270px" is-transparent>
				<div style="width: 95%;background-color:#fff;margin:0 auto;padding-bottom: 5px">
					<group>
						<checker v-model="level" style="margin-top: 20px" default-item-class="checkDefault" selected-item-class="checkDefaultSelected">
							<span style="margin-left: 5px;font-size: 13px;background-color: rgb(200, 2, 23);padding: 5px 5px; margin-right: 10px; color: white">选择评级</span>
							<checker-item :value="item" v-for="(item, index) in levelItems" :key="index">{{item.name}}</checker-item>
						</checker>
					</group>
					<div class="error" v-show="error">{{error}}</div>
					<flexbox>
						<flexbox-item>
							<x-button class="flexBtn_confirm" @click.native="confirmLevel">提交</x-button>
						</flexbox-item>
						<flexbox-item>
							<x-button class="flexBtn_cancel" @click.native="cancelLevel">取消</x-button>
						</flexbox-item>
					</flexbox>
				</div>
			</popup>
		</div>

		<div v-transfer-dom>
			<popup v-model="showStage" :hide-on-blur=false height="270px" is-transparent>
				<div style="width: 95%;background-color:#fff;margin:0 auto;padding-bottom: 5px">
					<group>
						<checker v-model="stage" style="margin-top: 20px" default-item-class="checkDefault" selected-item-class="checkDefaultSelected">
							<span style="margin-left: 5px;font-size: 13px;background-color: rgb(200, 2, 23);padding: 5px 5px; margin-right: 10px; color: white">选择阶段</span>
							<checker-item :value="item" v-for="(item, index) in stageItems" :key="index">{{item.name}}</checker-item>
						</checker>
					</group>
					<div class="error" v-show="error">{{error}}</div>
					<flexbox>
						<flexbox-item>
							<x-button class="flexBtn_confirm" @click.native="confirmStage">提交</x-button>
						</flexbox-item>
						<flexbox-item>
							<x-button class="flexBtn_cancel" @click.native="cancelStage">取消</x-button>
						</flexbox-item>
					</flexbox>
				</div>
			</popup>
		</div>
	</div>
</template>

<script>
	import Vue from 'vue'
	import DateUtil from '../../../utils/date'
	import NetWorking from '../../../utils/networking'
	import { Group, Cell, ConfirmPlugin, Tab, TabItem, FormPreview, Grid, GridItem, TransferDom, Popup, Flexbox, FlexboxItem, XButton, XTextarea, Checker, CheckerItem} from 'vux'
	import VueScroller from 'vue-scroller'
	Vue.use(VueScroller)
	Vue.use(ConfirmPlugin)

	const SIZE = 20

	export default {
		name: "scrollerAllPoCusCustomer",
		components: {
			Group,
			Cell,
			Tab,
			TabItem,
			FormPreview,
			Grid,
			GridItem,
			TransferDom,
			Popup,
			Flexbox,
			FlexboxItem,
			XButton,
			XTextarea,
			Checker,
			CheckerItem
		},
		directives: {
			TransferDom
		},
		props: ['curURL', 'jumpToObjectDetails', 'orderBy','sequence','status'],
		data() {
			return {
				error: '',
				isWechat: false,
				id: '',
				detail: '',
				hint: '通话详细内容',
				showPopup: false,
				showIfConnected: false,
				action: {name: '继续跟踪', value: 0},
				actionItems: [{name: '继续跟踪', value: 0}, {name: '转为客户', value: 1}, {name: '丢弃', value: '3'}],
				showLevel: false,
				level: '',
				levelItems: [],
				showStage: false,
				stage: '',
				stageItems: [],
				noDataText: '',
				offset: 0,
				limit: SIZE,
				noMoreData: false,
				items: [],
				list: [],
				curItem: '',
				curIndex: 0
			}
		},
		created: function () {
			if(navigator.userAgent.match('MicroMessenger')){
				this.isWechat = true
			}
		},
		watch: {
			curURL: function () {
				this.resetData()
			},
			orderBy: function () {
				this.resetData()
			},
			sequence: function () {
				this.resetData()
			},
			status: function () {
				this.resetData()
			}
		},
		methods:{
			triggerrefresh()
			{
				this.noDataText = ''
				this.offset = 0
				this.limit = SIZE
				this.noMoreData = false
				this.items = []
				this.$refs.scrollerTrace.finishPullToRefresh(false)
				this.$refs.scrollerTrace.finishInfinite(false)
				this.infinite(done)
			},
			callCustomer: function (item,index) {
				if(this.isWechat){
					alert('该功能需要在APP中使用')
					return
				}else{
					let _this = this
					window.plugins.CallNumber.callNumber(function onSuccess(result){
							setTimeout(function(){
								_this.showPopup = true
								_this.id = item.id
								_this.curItem = item
								_this.curIndex = index
							}, 1000)
						},
						function onError(result) {
							alert("Error:call number"+result)
						},
						item.phone,true)
				}
			},
			connected: function () {
				this.showPopup = false
				this.showIfConnected = true
			},
			unconnected: function () {
				let _this = this
				NetWorking.doPost(
					'customertrace',
					null,
					null,
					{
						params: {
							content: '电话未接通' ,
							customerId: this.id
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.detail = ''
							_this.showPopup = false
							_this.updateItem(rs.trace)
						}else{
							alert(rs.error_message)
						}
					}
				)
			},
			updateItem: function (trace) {
				this.items[this.curIndex].time = trace.create_time
				this.items[this.curIndex].comments = trace.content
			},
			jumpTo: function (id) {
				//组件间传递参数
				this.$router.push({ name: "customerDetails", params: { id: id, index: 1}})
			},
			formatTime: function (time) {
				return DateUtil.getTimeWhile(time)
			},
			confirm: function () {
				if(this.action == ''){
					this.error = "请选择相应的操作"
					return
				}

				this.showIfConnected = false
				let curTime = DateUtil.getYYMMDDHHmm(new Date())
				var url_trace = 'customertrace'
				var url_act = 'activities/attachCallActivity'
				var url_cus = 'customers/updateCustomerField'
				var urlarr = new Array()
				urlarr.push(
					NetWorking.doPost(
						url_trace,
						null,
						null,
						{
							params: {
								content: this.detail ,
								customerId: this.id
							}
						}
					))

				urlarr.push(
					NetWorking.doPost(
						url_act,
						null,
						{
							title: '电话',
							content: this.detail,
							time: curTime,
							status: 2 //mark call status as 2 if we confirm we've called the customer
						},
						{
							params: {
								employee_id: this.$store.state.user.userModel.sysUser.id,
								customer_id: this.id,
								rolePlay: 'consultant'
							}
						}
					))

				urlarr.push(
					NetWorking.doPost(
						url_cus,
						null,
						null,
						{
							params: {
								id: this.id,
								fieldName: "status",
								fieldValue: this.action.value
							}
						}
					))

				let _this = this
				var callback = function (c1, c2, c3) {
					let rs1 = c1.data
					let rs2 = c2.data
					let rs3 = c3.data

					if(rs1.error_code != 0 || rs2.error_code != 0 || rs3.error_code != 0){
						alert('更新记录失败，请重试')
					}else{
						_this.detail = ''
						_this.show   = false
						_this.items[_this.curIndex].time = rs1.trace.create_time
						_this.items[_this.curIndex].comments = rs1.trace.content
					}
				}

				NetWorking.doAll2(urlarr).then(this.axios.spread(callback))
					.catch(function (e){
						console.log(2);
					});
			},
			cancel: function () {
				this.showIfConnected = false
			},
			showLevelPop: function (item, index) {

				let _this = this
				NetWorking.doGet(
					'list_of_value/getListOfValueByType',
					null,
					{
						params: {
							type: 'S_LOV_OPP_LEVEL'
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.levelItems = []
							let items = rs.list_of_value

							for(let i=0; i<items.length; i++){
								_this.levelItems.push({name: items[i].value, value: items[i].value})
							}

							this.id = item.id
							this.curItem = item
							this.curIndex = index
							this.showLevel = true

						}else{
							alert(rs.error_message)
						}
					}
				)
			},
			confirmLevel: function () {
				let _this = this
				if(this.level == ''){
					this.error = "请选择相应的评级"
					return
				}

				NetWorking.doPost(
					'customers/updateCustomerField',
					null,
					null,
					{
						params: {
							id: this.id,
							fieldName: "tag",
							fieldValue: this.level.value
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.items[_this.curIndex].tag = rs.customer.tag
							this.level = ''
							this.showLevel = false
						}else{
							alert(rs.error_message)
						}
					}
				)
			},
			cancelLevel: function () {
				this.level = ''
				this.showLevel = false
			},
			showStagePop: function (item, index) {

				let _this = this
				NetWorking.doGet(
					'list_of_value/getListOfValueByType',
					null,
					{
						params: {
							type: 'S_LOV_OPP_STAGE'
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.stageItems = []
							let items = rs.list_of_value

							for(let i=0; i<items.length; i++){
								_this.stageItems.push({name: items[i].value, value: items[i].id})
							}

							this.id = item.id
							this.curItem = item
							this.curIndex = index
							this.showStage = true

						}else{
							alert(rs.error_message)
						}
					}
				)
			},
			confirmStage: function () {
				let _this = this
				if(this.stage == ''){
					this.error = "请选择相应的阶段"
					return
				}

				NetWorking.doPost(
					'customers/updateCustomerField',
					null,
					null,
					{
						params: {
							id: this.id,
							fieldName: "stage_id",
							fieldValue: this.stage.value
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.items[_this.curIndex].stage = this.stage.name
							this.stage = ''
							this.showStage = false
						}else{
							alert(rs.error_message)
						}
					}
				)
			},
			cancelStage: function () {
				this.stage = ''
				this.showStage = false
			},
			orderByFunc: function (value) {
				this.orderBy = value
				if(this.sequence == 'asc'){
					this.sequence = 'desc'
				}else{
					this.sequence = 'asc'
				}
				sessionStorage.orderBy = this.orderBy
				sessionStorage.sequence = this.sequence
			},
			resetData() {
				this.noDataText = ''
				this.offset = 0
				this.limit = SIZE
				this.noMoreData = false
				this.items = []
				this.$refs.poStudentList.finishPullToRefresh(false)
				this.$refs.poStudentList.finishInfinite(false)
			},
			refresh (done) {
				this.$refs.poStudentList.finishPullToRefresh(true)
				return
			},
			infinite (done) {
				if(this.noMoreData){
					this.noDataText = '没有更多记录了——总' + this.items.length + '条'
					this.$refs.poStudentList.finishInfinite(true)
					return
				}else{
					let _this = this
					_this.offset += 1
					this.isRunning = true
					NetWorking.doGet(
						this.curURL,
						null ,
						{
							params:{
								offset: _this.offset,
								limit: _this.limit,
								orderBy: _this.orderBy,
								sequence: _this.sequence,
								status: _this.status
							}
						}
					).then(
						response => {
							let res = response.data
							if (res.error_code == 0) {
								if(res.page_info.list.length >= 0){
									_this.items.push.apply(_this.items, res.page_info.list)
									_this.bottom += res.page_info.list.length
									//set noMoreData flag to true if current size < limit
									if(res.page_info.list.length < _this.limit){
										_this.noMoreData = true
										_this.$refs.poStudentList.finishInfinite(true);
									}
								}
							} else {
								alert(res.error_message)
							}
							done()
						}
					)
				}
			}
		}
	}
</script>

<style>
	.commonScrollerAllPoCustomer{
		margin-top: 81px;
	}

	.myPoCusGridTitle{
		font-size: 12px;
		background: lightgoldenrodyellow;
		z-index: 10;
	}

	.myPoCusGridTitle > .weui-grid {
		width: 15% !important;
	}

	.myPoCusGridTitle > .myPoCusStatus {
		width: 40% !important;
	}

	.myPoCusGrid {
		font-size: 12px;
	}

	.myPoCusGrid > .weui-grid {
		text-decoration: none;
	}

	.myPoCusGrid > .weui-grid {
		width: 15% !important;
	}

	.myPoCusGrid > .myPoCusStatus {
		width: 40% !important;
	}

	.myPoCusGrid > .myPoCusStatus:after{
		border-bottom: 0px solid #D9D9D9 !important;
	}

	.grid-center {
		display: block;
		text-align: center;
		color: #666;
	}

	.grid-center-status {
		display: block;
		text-align: center;
		color: #b29a19;
	}

	.grid-center-name{
		display: block;
		text-align: center;
		color: #43abe3;
	}

	.poStudentList {
		margin-top: 76px;
	}

	.poStudentList > .weui-cells:before {
		border-top: none;
	}

	.tag {
		text-align: right;
		background: red;
		width: fit-content;
		color: white;
		padding-left: 5px;
		border-radius: 5px;
		padding-right: 5px;
		font-size: 13px;
	}

	.itemTime {
		display: block;
		-webkit-margin-before: 1em;
		-webkit-margin-after: 1em;
		-webkit-margin-start: 0px;
		-webkit-margin-end: 0px;
		line-height: 1.41176471;
		font-size: 13px;
	}

	.checkDefault {
		border: 1px solid #ececec;
		padding: 5px 5px;
		background-color: white;
		margin-right: 10px;
		font-size: 13px;
		margin-bottom: 10px;
	}

	.checkDefaultSelected {
		background: #ffffff url(../../../assets/img/icon_check.png) no-repeat right bottom;
		border-color: #ff4a00;
	}
</style>